package study.alex.resumedb.gae.model;

import javax.persistence.jpa21.AttributeConverter;
import javax.persistence.jpa21.Converter;
import java.util.GregorianCalendar;

/**
 * Created with IntelliJ IDEA.
 * User: alex
 * Date: 29.01.14
 * Time: 15:05
 * SVN $Id$
 */

public class GregorianCalendarConverter implements AttributeConverter<GregorianCalendar, String> {
    @Override
    public String convertToDatabaseColumn(GregorianCalendar attributeObject) {
        return (attributeObject == null) ? null : ((Long)attributeObject.getTimeInMillis()).toString();
    }

    @Override
    public GregorianCalendar convertToEntityAttribute(String dbData) {
        if (dbData == null) return null;
        GregorianCalendar gr = new GregorianCalendar();
        Long millis = null;
        try {
            millis = Long.parseLong(dbData);
        } catch (NumberFormatException e) {
            throw new IllegalStateException("Error converting the GregorianCalendar", e);
        }
        gr.setTimeInMillis(millis);
        return gr;
    }
}
